package com.xuequ.answerme.manager;

import android.content.Context;
import android.support.v4.util.TimeUtils;
import android.util.Log;
import android.widget.Toast;

import com.xuequ.answerme.beans.QuestionBean;
import com.xuequ.answerme.tools.Tools;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by Shijie on 2015/10/2.
 */
public class QuestionManager {


    //提问监听
    public interface AskQuestionListener {
        void AskQuestionOnSuccess();// 添加成功

        void AskQuestionOnFailure(String failureMSG);// 添加失败返回失败信息
    }

    //修改问题

    //模糊查找问题
    public interface FuzzySearchQuestionListener {
        void fuzzySearchQuestionOnSuccess(List<QuestionBean> questions);// 查找成功返回Questions列表

        void fuzzySearchQuestionOnFailure(String failureMsg);// 查找失败返回失败信息
    }

    //
    public interface FindNewQuestionsListener {
        void findNewQuestionsOnSuccess(List<QuestionBean> questionBeans);

        void findNewQuestionsOnFailure(String failureMsg);
    }

    public interface FindMuchFocusQuestionsListener {
        void findMuchFocusQuestionsOnSuccess(List<QuestionBean> questionBeans);

        void findMuchFocusQuestionsOnFailure(String failureMsg);
    }

    //关注
    public interface FocusOrNotListener {
        void focusOrNotOnSuccess();

        void focusOrNotOnFailure(String failureMsg);
    }

    public interface AnswerOrNotListener {
        void answerOrNotOnSuccess();

        void answerOrNotOnFailure(String failureMsg);
    }

    public interface FindMuchSearchQuestionsListener {
        void findMuchSearchQuestionsOnSuccess(List<QuestionBean> questionBeans);

        void findMuchSearchQuestionsOnFailure(String failureMsg);
    }

    public interface LoadMoreQuestionsListener {
        void loadMoreQuestionsOnSuccess(List<QuestionBean> questionBeans);

        void loadMoreQuestionsOnFailure(String failureMsg);
    }

    public interface CheckTheQuestionListener{
        void checkTheQuestionOnSuccess(QuestionBean questionBean);
        void checkTheQuestionOnFailure(String failureMsg);
    }


    /**
     * 提问题。
     * （在调用方法之前就要检测QuestionBean的合法性。）
     * （在问题人在提问输入问题时，我们做实时模糊查找，推荐类似题目，可避免问题的重复）
     *
     * @param context             上下文
     * @param questionBean        问题
     * @param askQuestionListener 提问题listener
     */
    public void askQuestion(Context context, QuestionBean questionBean, final AskQuestionListener askQuestionListener) {
        if (Tools.isNetAvailable(context)) {
            questionBean.save(context, new SaveListener() {
                @Override
                public void onSuccess() {
                    askQuestionListener.AskQuestionOnSuccess();
                }

                @Override
                public void onFailure(int i, String s) {
                    askQuestionListener.AskQuestionOnFailure(s);
                }
            });
        } else {
            askQuestionListener.AskQuestionOnFailure("网络不可用");
        }
    }

    /**
     * 在 用户查找 或 提问题输入问题 的时候调用的模糊查找方法。
     * （在问题人在提问输入问题时，我们做实时模糊查找，推荐类似题目，可避免问题的重复）
     *
     * @param context                     上下文
     * @param targetString                需要查找的目标字符串
     * @param fuzzySearchQuestionListener 模糊查找listener
     */
    public void fuzzySearchQuestion(Context context, String targetString, final FuzzySearchQuestionListener fuzzySearchQuestionListener) {

        BmobQuery<QuestionBean> questions = new BmobQuery<>();
        questions.addWhereContains("question_title", targetString);
        questions.include("questioner");
        questions.findObjects(context, new FindListener<QuestionBean>() {
            @Override
            public void onSuccess(List<QuestionBean> list) {
                fuzzySearchQuestionListener.fuzzySearchQuestionOnSuccess(list);
            }

            @Override
            public void onError(int i, String s) {
                fuzzySearchQuestionListener.fuzzySearchQuestionOnFailure(s);
            }
        });

    }

    /**
     * 查找最新的问题
     *
     * @param context                  上下文
     * @param findNewQuestionsListener 找最新问题的listener
     */
    public void findNewQuestions(Context context, String lastRefreshDate, final FindNewQuestionsListener findNewQuestionsListener) {
        if (Tools.isNetAvailable(context)) {
            BmobQuery<QuestionBean> questionBeans = new BmobQuery<>();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            try {
                date = sdf.parse(lastRefreshDate);
            } catch (Exception e) {

            }
            questionBeans.addWhereGreaterThan("createdAt", new BmobDate(date));
            questionBeans.order("-createdAt");
            questionBeans.include("questioner");
            questionBeans.setLimit(20);
            questionBeans.findObjects(context, new FindListener<QuestionBean>() {
                @Override
                public void onSuccess(List<QuestionBean> list) {
                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).setQuestion_createdAt(list.get(i).getCreatedAt());
                    }
                    findNewQuestionsListener.findNewQuestionsOnSuccess(list);
                }

                @Override
                public void onError(int i, String s) {
                    findNewQuestionsListener.findNewQuestionsOnFailure(s);
                }
            });
        } else {
            findNewQuestionsListener.findNewQuestionsOnFailure("网络不可用");
        }

    }

    /**
     * 是否关注此问题
     *
     * @param context            上下文
     * @param question_objectId  所关注问题的ID
     * @param isFocus            之前的关注状态
     * @param focusOrNotListener 监听器
     */
    public void focusNumberChange(Context context, String question_objectId, boolean isFocus, final FocusOrNotListener focusOrNotListener) {
        if (Tools.isNetAvailable(context)) {
            QuestionBean questionBean = new QuestionBean();
            questionBean.setObjectId(question_objectId);
            if (!isFocus) {
                //如果之前不是关注的，就关注，关注数增加1
                questionBean.increment("question_focus");
            } else {
                //如果之前是关注的，就取关，关注数减1
                questionBean.increment("question_focus", -1);
            }
            questionBean.update(context, new UpdateListener() {
                @Override
                public void onSuccess() {
                    focusOrNotListener.focusOrNotOnSuccess();
                }

                @Override
                public void onFailure(int i, String s) {
                    focusOrNotListener.focusOrNotOnFailure(s);
                }
            });
        } else {
            focusOrNotListener.focusOrNotOnFailure("网络不可用");
        }
    }

    /**
     * 找到一些关注数比较高的问题
     *
     * @param context                        上下文
     * @param findMuchFocusQuestionsListener 监听器
     */
    public void findMuchFocusQuestions(Context context, final FindMuchFocusQuestionsListener findMuchFocusQuestionsListener) {
        if (Tools.isNetAvailable(context)) {
            BmobQuery<QuestionBean> questionBeans = new BmobQuery<>();
            questionBeans.order("-question_focus");
            questionBeans.findObjects(context, new FindListener<QuestionBean>() {
                @Override
                public void onSuccess(List<QuestionBean> list) {
                    Log.i("findTen", " " + list.size());
                    findMuchFocusQuestionsListener.findMuchFocusQuestionsOnSuccess(list);
                }

                @Override
                public void onError(int i, String s) {
                    findMuchFocusQuestionsListener.findMuchFocusQuestionsOnFailure(s);
                }
            });
        } else {
            findMuchFocusQuestionsListener.findMuchFocusQuestionsOnFailure("网络不可用");
        }

    }

    /**
     * 第一次打开应时进行第一次的刷新
     *
     * @param context                  上下文
     * @param findNewQuestionsListener 监听器（借用FindNewQuestionsListener）
     */
    public void firstTimeFindNewQuestions(Context context, final FindNewQuestionsListener findNewQuestionsListener) {
        if (Tools.isNetAvailable(context)) {
            BmobQuery<QuestionBean> questionBeans = new BmobQuery<>();
            questionBeans.order("-createdAt");
            //第一次刷新只刷新前20个
            questionBeans.include("questioner");
            questionBeans.setLimit(20);
            questionBeans.findObjects(context, new FindListener<QuestionBean>() {
                @Override
                public void onSuccess(List<QuestionBean> list) {
                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).setQuestion_createdAt(list.get(i).getCreatedAt());
                    }
                    Log.i("findTen", " " + list.size());
                    findNewQuestionsListener.findNewQuestionsOnSuccess(list);
                }

                @Override
                public void onError(int i, String s) {
                    findNewQuestionsListener.findNewQuestionsOnFailure(s);
                }
            });
        } else {

            findNewQuestionsListener.findNewQuestionsOnFailure("网络不可用");
        }

    }

    /**
     * 此问题回答数改变
     *
     * @param context             上下文
     * @param question_objectId   所回答问题的ID
     * @param answerOrNot         回答或删除
     * @param answerOrNotListener 监听器
     */
    public void AnswerOrNot(Context context, String question_objectId, boolean answerOrNot, final AnswerOrNotListener answerOrNotListener) {
        if (Tools.isNetAvailable(context)) {
            QuestionBean questionBean = new QuestionBean();
            questionBean.setObjectId(question_objectId);
            if (answerOrNot) {
                //如果是回答，回答数+1
                questionBean.increment("question_answers");
            } else {
                //如果不是回答，回答数-1
                questionBean.increment("question_focus", -1);
            }
            questionBean.update(context, new UpdateListener() {
                @Override
                public void onSuccess() {
                    answerOrNotListener.answerOrNotOnSuccess();
                }

                @Override
                public void onFailure(int i, String s) {
                    answerOrNotListener.answerOrNotOnFailure(s);
                }
            });
        } else {
            answerOrNotListener.answerOrNotOnFailure("网络不可用");
        }
    }

    /**
     * 查找搜索次数高的5个问题
     *
     * @param context                         上下文
     * @param findMuchSearchQuestionsListener 监听器
     */
    public void findMuchSearchQuestions(Context context, final FindMuchSearchQuestionsListener findMuchSearchQuestionsListener) {
        if (Tools.isNetAvailable(context)) {
            BmobQuery<QuestionBean> questionBeans = new BmobQuery<>();
            questionBeans.setLimit(10);
            questionBeans.order("-question_search");
            questionBeans.findObjects(context, new FindListener<QuestionBean>() {
                @Override
                public void onSuccess(List<QuestionBean> list) {
                    Log.i("findTen", " " + list.size());
                    findMuchSearchQuestionsListener.findMuchSearchQuestionsOnSuccess(list);
                }

                @Override
                public void onError(int i, String s) {
                    findMuchSearchQuestionsListener.findMuchSearchQuestionsOnFailure(s);
                }
            });
        } else {
            findMuchSearchQuestionsListener.findMuchSearchQuestionsOnFailure("网络不可用");
        }

    }

    /**
     * @param context
     * @param earliestQuestion_createdAt
     * @param loadMoreQuestionsListener
     */
    public void loadMoreQuestions(Context context, String earliestQuestion_createdAt, final LoadMoreQuestionsListener loadMoreQuestionsListener) {
        if (Tools.isNetAvailable(context)) {

            BmobQuery<QuestionBean> questions = new BmobQuery<>();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            try {
                date = sdf.parse(earliestQuestion_createdAt);
            } catch (Exception e) {

            }
            questions.addWhereLessThan("createdAt", new BmobDate(date));
            questions.order("-createdAt");
            questions.setLimit(10);
            questions.include("questioner");
            questions.findObjects(context, new FindListener<QuestionBean>() {
                @Override
                public void onSuccess(List<QuestionBean> list) {
                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).setQuestion_createdAt(list.get(i).getCreatedAt());
                    }
                    loadMoreQuestionsListener.loadMoreQuestionsOnSuccess(list);
                }

                @Override
                public void onError(int i, String s) {
                    loadMoreQuestionsListener.loadMoreQuestionsOnFailure(s);
                }
            });

        } else {
            loadMoreQuestionsListener.loadMoreQuestionsOnFailure("网络不可用");
        }

    }

    /**
     * 检测问题是否存在
     *
     * @param context
     * @param question_objectId
     * @param checkTheQuestionListener
     */
    public void checkTheQuestion(Context context, String question_objectId, final CheckTheQuestionListener checkTheQuestionListener){

        if(Tools.isNetAvailable(context)){
            BmobQuery<QuestionBean> questionBean = new BmobQuery<>();
            questionBean.include("questioner");
            questionBean.getObject(context, question_objectId, new GetListener<QuestionBean>() {
                @Override
                public void onSuccess(QuestionBean questionBean) {
                    checkTheQuestionListener.checkTheQuestionOnSuccess(questionBean);
                }

                @Override
                public void onFailure(int i, String s) {
                    checkTheQuestionListener.checkTheQuestionOnFailure(s);
                }
            });
        }else {
            checkTheQuestionListener.checkTheQuestionOnFailure("网络不可用");
        }

    }

}
